﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.Remoting.Messaging;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using ExcelFORM = Microsoft.Office.Interop.Excel;
using System.Reflection; 
using System.Collections;
using System.Data.SqlClient;
using System.Security.Permissions;
using OfficeOpenXml;

namespace ServerAnalysisReport
{
    public partial class MainForm1 : Form
    {
        public delegate ArrayList delegateRunSingleQueueJob(int[] targetmetricid, string datemin, string datemax, int timeout);

        public delegate string sqlcalldelegate();
        private static readonly int[] metricids = { 5, 7, 8, 9, 10 };
        public MainForm1()
        {
            InitializeComponent();
            ThreadPool.SetMaxThreads(1, 1);
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
           // GenerateReport();
            string StartDate = StartDateBox.Value.Month + "-" + StartDateBox.Value.Day + "-" + StartDateBox.Value.Year;
            string EndDate = EndDateBox.Value.Month + "-" + EndDateBox.Value.Day + "-" + EndDateBox.Value.Year;
            ArrayList ServerNameAR = new ArrayList();

            foreach (string servername in ServerListBox1.CheckedItems)
            {
                ServerNameAR.Add(servername);
            }
            DataBase DB = new DataBase(ServerNameAR);
            delegateRunSingleQueueJob dQueueJob = DB.RunSingleQueueJob;
            AsyncCallback LocalACallback = ACallback;
            dQueueJob.BeginInvoke(metricids, StartDate,EndDate,Convert.ToInt16(QueryTimeOut.Text), LocalACallback, null);

        }

        private bool GenerateReport(ArrayList TotalServerStats)
        {
            //ExcelPackage xlPackage = new ExcelPackage(new FileInfo("test.xls")); 


            ExcelFORM.Application oXL;
            ExcelFORM._Workbook oWB;
            ExcelFORM._Worksheet oSheet;
            ExcelFORM.Range oRng;


            foreach (ArrayList SingleMetricStats in TotalServerStats)
            {

                //MessageBox.Show("Generating Report for Server " + servername);

                try
                {
                    //Start Excel and get Application object.
                    oXL = new ExcelFORM.Application();
                    oXL.Visible = true;
                    
                    oWB = oXL.Workbooks.Add(Missing.Value);

                    //int timeout = 30;
                    //oWB.Name = TargetServerBox.SelectedText.ToString();
                    //if ((Convert.ToInt32(QueryTimeOut.Text) > 29) && (Convert.ToInt32(QueryTimeOut.Text) < 65536))
                    //{
                    //    timeout = Convert.ToInt32(QueryTimeOut.Text);
                    //}
                    //else
                    //{
                    //    MessageBox.Show("You have entered out of range timeout value : " + QueryTimeOut.Text + "\nPlease enter the value between 30-65536\nDefault Value of 30 will be used for current query");
                    //}

                    foreach (int metric in metricids)
                    {

                        //Get a new workbook.
                        oSheet = (ExcelFORM._Worksheet)oWB.Worksheets.Add(Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                        switch (metric)
                        {
                            case 5:
                                oSheet.Name = metric + " Pages Per Sec";
                                break;
                            case 7:
                                oSheet.Name = metric + " Context Switches";
                                break;
                            case 8:
                                oSheet.Name = metric + " Inactive Sessions";
                                break;
                            case 9:
                                oSheet.Name = metric + " Active Sessions";
                                break;
                            case 10:
                                oSheet.Name = metric + " % Processor Time";
                                break;

                            default:
                                oSheet.Name = "No Metric specified ";
                                break;
                        }


                        oSheet = (ExcelFORM._Worksheet)oWB.ActiveSheet;

                        int rowcounter = 3;
                        foreach (string[] stats in SingleMetricStats)
                        {

                            if (stats == null)
                            {
                                break;
                            }
                            int column = 1;
                            foreach (string stat in stats)
                            {
                                try
                                {
                                    if (stat == null)
                                    {
                                        break;
                                    }
                                    oSheet.Cells[rowcounter, column] = stat;

                                    column++;
                                }
                                catch (Exception exx)
                                {
                                    MessageBox.Show("stat" + stats[0] + " " + stats[1] + " " + stats[3] + " " + stats[4] + " " + stats[5] + " " + stats[6]);
                                    MessageBox.Show("error " + exx);
                                }

                            }
                            rowcounter++;
                        }//end foreach
                        //Add table headers going cell by cell.
                        oSheet.Cells[1, 1] = "Server Name";
                        oSheet.Cells[1, 2] = "";
                        oSheet.Cells[2, 1] = "Date GMT0";
                        oSheet.Cells[2, 2] = "GMT BIASTIME";
                        oSheet.Cells[2, 3] = "METRIC DURATION (SEC)";
                        oSheet.Cells[2, 4] = "MIN";
                        oSheet.Cells[2, 5] = "MAX";
                        oSheet.Cells[2, 6] = "MEAN";
                        oSheet.Cells[2, 7] = "STD DEV";

                        oRng = oSheet.get_Range("A:A", Missing.Value);
                        oRng.NumberFormat = "dd/mm/yyyy h:mm";
                        oRng.EntireColumn.AutoFit();
                        oRng = oSheet.get_Range("D:G", Missing.Value);
                        oRng.NumberFormat = "0.000000000000";
                        oRng.EntireColumn.AutoFit();


                    }//end foreach metricids

                    oXL.Visible = true;
                    oXL.UserControl = true;

                }
                catch (Exception theException)
                {
                    String errorMessage;
                    errorMessage = "Error: ";
                    errorMessage = String.Concat(errorMessage, theException.Message);
                    errorMessage = String.Concat(errorMessage, " Line: ");
                    errorMessage = String.Concat(errorMessage, theException.Source);

                    MessageBox.Show(errorMessage, "Error");

                    return false;
                }
            }
            return true;
        }




        private void ServerListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
         
            if ((ServerListBox1.CheckedItems.Count > 4) && (ServerListBox1.GetItemCheckState(e.Index) == CheckState.Unchecked) )
            {
                MessageBox.Show("Please try to limit selection to less than 5 items", "Warning",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }
        }

        private void serverListingToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Config ConfigForm = new Config();
            ConfigForm.Show();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            AboutBox ab = new AboutBox();
            ab.Show();
        }

        private void ACallback(IAsyncResult iar)
        {
            AsyncResult ar = (AsyncResult)iar;
            delegateRunSingleQueueJob localdelegate = (delegateRunSingleQueueJob)ar.AsyncDelegate;
            
            //GenerateReport(localdelegate.EndInvoke(iar));
            GenerateExcel.createExcelReport(localdelegate.EndInvoke(iar));
            //GenerateExcel.createCSVReport("temp.csv", localdelegate.EndInvoke(iar));
        }


    }
}
